package com.hewep.demo.nio;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.List;


public class Reader implements Runnable {

	//读线程中的可读的通道池
	private static List<SelectionKey> pool = new LinkedList<SelectionKey>();
	private static final int MAX_CAPACITY = 1024;
	private static Notify notify = Notify.getInstance();
	
	public Reader(){
		
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (true){
			try{
				SelectionKey key;
				synchronized (pool) {
					while (pool.isEmpty()) {
						pool.wait();
					}
					key = pool.remove(0);
				}
				read(key);
				
			}catch (InterruptedException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}
	
	public void read(SelectionKey key){
		
		try{
			SocketChannel sc = (SocketChannel) key.channel();
			byte[] clientData = readRequest(sc);
			Request request = new Request(sc);
			request.setDataInput(clientData);
			
			//触发读事件,将request包装起来发给具体需要处理的业务逻辑
			notify.fireOnRead(request);
			
			// 提交主控线程进行写处理，就是通知主线程，通道中的信息我已经读完了，可以进行写入了。
            Server.processWriteRequest(key);
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public byte[] readRequest(SocketChannel sc) throws Exception{
		
		ByteBuffer buffer = ByteBuffer.allocate(MAX_CAPACITY);
		sc.read(buffer);
		byte[] req = new byte[MAX_CAPACITY * 10];
		req = buffer.array();
		
		return req;	
	}

	//当有可以被读的通道进来时，加入到通道池中，然后唤醒通道池以便处理
	public static void processRequest(SelectionKey key){
		synchronized (pool) {
			pool.add(pool.size(), key);
			pool.notifyAll();
		}
	}
}
